<?php

namespace app\service\websocket;

use think\Exception;

/**
 * 处理消息机制
 *
 * Class Entry
 *
 * @package app\service\websocket
 */
class Entry
{
    public static function open( \swoole_websocket_server $server, \swoole_http_request $request )
    {
        // TODO: 先不做处理
        // echo $request->fd . '连上来了' . PHP_EOL;
        echo $request->fd . '上线了' . PHP_EOL;
    }

    /**
     * websocket消息处理
     *
     * @param \swoole_websocket_server $server
     * @param \swoole_websocket_frame  $frame
     */
    public static function message( \swoole_websocket_server $server, \swoole_websocket_frame $frame )
    {
        // 消息分发机制
        try
        {
            Handler::getInstance( $server )->dispatch( $frame );
        }
        catch ( Exception $e )
        {
            $server->exist( $frame->fd ) && $server->push( $frame->fd, json_encode( [
                'type'    => 'system_error',
                'message' => $e->getMessage() . $e->getFile() . $e->getLine()
            ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ) );
        }
    }

    /**
     * 当客户端或者服务器关闭客户端时候触发
     *
     * @param \swoole_websocket_server $server
     * @param                          $fd
     */
    public static function close( \swoole_websocket_server $server, $fd )
    {
        // 处理关闭的逻辑
        Handler::getInstance( $server )->close( $fd );
    }
}